package com.itboye.textileexpres.myset;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.Html;
import android.text.Html.ImageGetter;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.textileexpres.widget.FaceInputView;
import com.example.textileexpres.widget.FaceInputView.Face;
import com.example.textileexpres.widget.FaceInputView.OnFaceClickListener;
import com.itboye.textileexpes.adapter.CustomAdapter;
import com.itboye.textileexpes.beans.ChatBean;
import com.itboye.textileexpes.beans.PeopleStudentBean;
import com.itboye.textileexpes.beans.PeopleTeacherBean;
import com.itboye.textileexpres.R;
import com.itboye.textileexpres.base.BaseActivity;
import com.itboye.textileexpres.util.ActionItem;
import com.itboye.textileexpres.util.CameraPopupWindow;
import com.itboye.textileexpres.util.FileUtils;
import com.itboye.textileexpres.util.PhotoSelectFragment;
import com.itboye.textileexpres.util.PhotoSelectFragment.PhotoSelectListener;
import com.itboye.textileexpres.util.TitlePopup;
import com.itboye.textileexpres.util.TitlePopup.OnItemOnClickListener;

public class ActivityKefu extends BaseActivity implements OnClickListener{

	private LinkedList<PeopleStudentBean> sList = null;
	private LinkedList<PeopleTeacherBean> tList = null;
	private ChatBean beans = null;

	// ** ����message ��ʽ *//
	private ListView lv;
	// ** ��Ϣ�༭�� *//*
	private EditText input;
	// ** ��Ϣ���Ͱ�ť *//*
	private TextView btnEnter;

	private CustomAdapter adapter;

	//
	View addImg;
	View addEmoj;
	FaceInputView faceInputView;

	ViewGroup bottom;
	LinearLayout selectImgContainer;
	LinearLayout imgPhoto;
	HorizontalScrollView horizontalScrollView;
	Integer gentiePosition = null;
	protected CameraPopupWindow mCameraPopupWindow;
	private File mCameraImageFile;// ��������յõ���ͼƬ
	private FileUtils mFileUtils;
	private final int REQUEST_CODE_CAPTURE_CAMEIA = 100;
	private final int REQUEST_CODE_PICK_IMAGE = 200;
	private String keFuId = null;
	String lastCreateTime;
	ArrayList<ChatBean.ChatItem> arrayList = new ArrayList<ChatBean.ChatItem>();
	private int pageNo = 1;
	// private SwipeRefreshLayout mSwipeLayout;

	int count = 0;

	// topImageView
	ImageView img_other;
	private TextView title;
	// 定义标题栏弹窗按钮
	private TitlePopup titlePopup;

	@Override
	public int initView() {
		// TODO Auto-generated method stub
		return R.layout.activity_kefu_messge;
	}

	@Override
	public void onMyCreate() {
		lv.setTranscriptMode(ListView.TRANSCRIPT_MODE_NORMAL);
		// TODO Auto-generated method stub
		mFileUtils = new FileUtils(this);
		sList = new LinkedList<PeopleStudentBean>();
		tList = new LinkedList<PeopleTeacherBean>();
		// 实例化标题栏弹窗
		titlePopup = new TitlePopup(this, LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT);

		TextViewEdittext();
		onImageVIew();
		initData();
		iniView();

	}

	/*
	 * PupopWindow初始化
	 */
	private void initData() {
		title.setText("客服");
		// 给标题栏弹窗添加子类
		titlePopup.addAction(new ActionItem(this, "客服消息"));
		titlePopup.addAction(new ActionItem(this, "所有客服"));
//		titlePopup.addAction(new ActionItem(this, "登录网页"));
//		titlePopup.addAction(new ActionItem(this, "扫一扫"));
		titlePopup.setItemOnClickListener(new OnItemOnClickListener() {

			@Override
			public void onItemClick(ActionItem item, int position) {
				// TODO Auto-generated method stub
				switch (position) {
				case 0:
					toast("" + position);

					Intent intent=new Intent(ActivityKefu.this,ActivityCustomerService.class);
					intent.putExtra("index",1);
					startActivity(intent);
					break;

				case 1:
					toast("" + position);
				

				default:
					break;
				}

			}
		});
	}

	/**
	 * 给Top设置图片
	 */
	public void onImageVIew() {
		img_other.setImageResource(R.drawable.goods_more);
		img_other.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				titlePopup.show(v);
			}
		});

	}

	/**
	 * 表情图片弹出窗
	 */
	public void iniView() {
		input.setOnFocusChangeListener(new android.view.View.OnFocusChangeListener() {
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if (hasFocus) {
					// 软键盘隐藏
					InputMethodManager inputMethodManager = (InputMethodManager) v
							.getContext().getSystemService(
									Context.INPUT_METHOD_SERVICE);

					if (inputMethodManager.isActive()) {
						inputMethodManager.hideSoftInputFromWindow(
								input.getWindowToken(), 0);
					}
					// 此处为得到焦点时的处理内容
				} else {
					System.out.println("失去了 焦点");
					// 此处为失去焦点时的处理内容
				}
			}
		});
		addEmoj.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				v.setSelected(!v.isSelected());
				if (faceInputView == null) {
					faceInputView = new FaceInputView(ActivityKefu.this);
					bottom.addView(faceInputView);
					faceInputView.setOnClickListener(new FaceInputListenr());
				}
				if (v.isSelected()) {
					if (bottom.getChildCount() == 2) {
						bottom.getChildAt(1).setVisibility(View.GONE);
					} else if (bottom.getChildCount() == 3) {
						bottom.getChildAt(1).setVisibility(View.GONE);
						bottom.getChildAt(2).setVisibility(View.GONE);
					}
					// 软键盘隐藏
					InputMethodManager inputMethodManager = (InputMethodManager) v
							.getContext().getSystemService(
									Context.INPUT_METHOD_SERVICE);

					if (inputMethodManager.isActive()) {
						inputMethodManager.hideSoftInputFromWindow(
								input.getWindowToken(), 0);
					}

					faceInputView.setVisibility(View.VISIBLE);
					addImg.setSelected(false);

				} else {
					faceInputView.setVisibility(View.GONE);

				}
			}
		});

		addImg.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (selectImgContainer == null) {
					horizontalScrollView = (HorizontalScrollView) ActivityKefu.this
							.getLayoutInflater().inflate(
									R.layout.item_producenter_kefu_select,
									bottom, false);
					bottom.addView(horizontalScrollView);
					selectImgContainer = (LinearLayout) horizontalScrollView
							.getChildAt(0);

					selectImgContainer.getChildAt(0).setOnClickListener(
							new OnClickListener() {

								@Override
								public void onClick(View v) {

									// onimgPhoto(v);
									openCamera();
								}
							});
					selectImgContainer.getChildAt(1).setOnClickListener(
							new OnClickListener() {

								@Override
								public void onClick(View v) {
									new PhotoSelectFragment(listener, 3).show(
											ActivityKefu.this
													.getSupportFragmentManager(),
											null);
								}
							});

				}
				addImg.setSelected(!addImg.isSelected());
				if (addImg.isSelected()) {
					if (bottom.getChildCount() == 2) {
						bottom.getChildAt(1).setVisibility(View.GONE);
					} else if (bottom.getChildCount() == 3) {
						bottom.getChildAt(1).setVisibility(View.GONE);
						bottom.getChildAt(2).setVisibility(View.GONE);
					}
					((View) selectImgContainer.getParent())
							.setVisibility(View.VISIBLE);
					addEmoj.setSelected(false);
				} else {
					((View) selectImgContainer.getParent())
							.setVisibility(View.GONE);
				}
			}

		});
	}

	// �����
	private void openCamera() {
		try {
			File PHOTO_DIR = new File(mFileUtils.getStorageDirectory());
			if (!PHOTO_DIR.exists())
				PHOTO_DIR.mkdirs();// ������Ƭ�Ĵ洢Ŀ¼

			mCameraImageFile = new File(PHOTO_DIR, getPhotoFileName());// �����յ���Ƭ�ļ�����
			final Intent intent = getTakePickIntent(mCameraImageFile);
			startActivityForResult(intent, REQUEST_CODE_CAPTURE_CAMEIA);
		} catch (ActivityNotFoundException e) {
		}
	}

	private Intent getTakePickIntent(File f) {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
		return intent;
	}

	/**
	 * �õ�ǰʱ���ȡ�õ�ͼƬ����
	 */
	private String getPhotoFileName() {
		Date date = new Date(System.currentTimeMillis());
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"'IMG'_yyyy_MM_dd_HH_mm_ss");
		return dateFormat.format(date) + ".jpg";
	}

	private void TextViewEdittext() {
		InputMethodManager inputMethodManager = (InputMethodManager) this
				.getSystemService(Context.INPUT_METHOD_SERVICE);

		if (inputMethodManager.isActive()) {
			inputMethodManager.hideSoftInputFromWindow(input.getWindowToken(),
					0);
		}
	}

	private PhotoSelectListener listener = new PhotoSelectListener() {

		@Override
		public void onPhotoSelectFinish(final List<String> paths) {
			// TODO Auto-generated method stub
			// if (keFuId == null) {
			// ByAlert.alert("�ͷ������ߣ����Ժ�����...");
			//
			//
			// return;
			// }
			showProgressDialog("图片上传中....", true);
			// path = paths;
			// countImg=0;
			// for (final String string : paths) {
			// // adapter.addItemNotifiChange(new
			// // Bean(mFileUtils.getFilePathFromUri(Uri
			// // .parse(string)), R.drawable.me,
			// // new Date() + "", 0));
			// countImg++;
			// ImageCompressAndUpload.getInstance().execute(string,
			// new OnUploadlistener() {
			//
			// @Override
			// public void OnSuccess(String resultData) {
			// uploadedUrl.add(resultData);
			// sendImageIdToServer(resultData, string);
			// DebugLog.v("bytag", resultData);
			// if (countImg == paths.size()) {
			// try {
			//
			// closeProgressDialog();
			// } catch (Exception e) {
			// // TODO: handle exception
			// }
			//
			// imgId.append(resultData + ",");
			// ByAlert.alert("ͼƬ�ϴ��ɹ�");
			// // sendToServer();
			// }
			// }
			//
			// @Override
			// public void OnError(String resultData) {
			// ByAlert.alert(resultData + "error");
			// try {
			// closeProgressDialog();
			//
			// } catch (Exception e) {
			// // TODO: handle exception
			// }
			// }
			// });

			// }
		}
	};

	// ���������Ҫ
	ImageGetter imageGetter = new ImageGetter() {
		@Override
		public Drawable getDrawable(String source) {
			int id = Integer.parseInt(source);
			Drawable d = getResources().getDrawable(id);
			d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
			return d;
		}
	};

	private class FaceInputListenr implements OnFaceClickListener {

		@Override
		public void selectedFace(Face face) {
			int id = face.faceId;
			if (id == R.drawable.face_del_ico_dafeult)// ɾ����ť
			{
				int index = input.getSelectionStart();
				if (index == 0)
					return;
				Editable editable = input.getText();
				editable.delete(index - 1, index);// ɾ�����һ���ַ������
			} else {
				input.append(Html.fromHtml("<img src='" + id + "'/>",
						imageGetter, null));// ��ӱ���
			}
		}

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.img_other:
			this.finish();
			break;

		default:
			break;
		}
	}

}
